package com.trainoo.service;

import com.trainoo.exception.GirlsException;
import com.trainoo.repository.GirlRepository;
import com.trainoo.domain.ResultEnum;
import com.trainoo.domain.Girl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

/**
 * Created by Administrator on 2017/6/5.
 */
@Service
public class GirlService {

    @Autowired
    private GirlRepository girlRepository;

    /**
     * 测试事务，由于CupSize长度数据库限制大小是1，所以g2插入失败，数据回滚
     *
     * 加入注解后任然没有效果？
     * 检查MySQL使用的引擎是否为InnoDB，如果不是，则修改成这个。MyISAM是不支持事务操作的
     *
     * show engines;
     * 在[mysqld]最后添加为上default-storage-engine=InnoDB，重启服务
     *
     */
    @Transactional
    public void insertTwo(){
        Girl g1 = new Girl();
        g1.setAge(12);
        g1.setCupSize("A");
        girlRepository.save(g1);

        Girl g2 = new Girl();
        g2.setAge(13);
        g2.setCupSize("33A");
        girlRepository.save(g2);

    }


    /*
        測試統一異常處理
     */
    public void getOne() throws Exception{
        Girl girl = girlRepository.findOne(10);
        System.out.println("find_: " + girl);
        if (girl.getAge() < 12){
            throw new GirlsException(ResultEnum.PRIMARY_SCHOOL);
        }else if(girl.getAge() > 12 && girl.getAge() < 16){
            throw new GirlsException(ResultEnum.MIDDLE_SCHOOL);
        }else{
            throw new GirlsException(ResultEnum.UNKONW);
        }
        //throw new Exception();
    }

    public Girl findOne(){
        return girlRepository.findOne(10);
    }
}
